#!/usr/bin/env python
#coding=UTF-8
'''
Created on 2010-11-5

@author: zarra
'''
from numpy import mat,sqrt
from common import safe_edge_get,Question
from noise import Salt_Pepper,Gaussian
import cv
 
class Spatial_Filter(object):
    def __init__(self,mask):
        self.mask = mask
        self.width = mask.shape[-1]
        self.n=self.width/2
        self.count =0
        for y in range(self.width):
            for x in range(self.width):
                self.count += self.mask[y,x]
                
    def process_pixel(self,X,Y):
        n=self.n
        v=list()
        for y in range(self.width):
            for x in range(self.width):
                offset_x = x-n
                offset_y = y-n
                p=safe_edge_get(self.image,X+offset_x,Y+offset_y)*self.mask[y,x]
                v.append(p)
        self.dst_image[Y,X] = self.process(v)
              
    def process(self,v):
        return v[0]    
    
    def __call__(self,src):
        self.image = src
        self.dst_image =  cv.CreateImage((src.width,src.height), src.depth, src.channels)
        for y in range(src.height):
            for x in range(src.width):
                self.process_pixel(x, y)
        return self.dst_image
    
class Mean_Filter(Spatial_Filter):
    def __init__(self,mask):
        super(self.__class__,self).__init__(mask)  
    
    def process(self,v):
        sum = reduce(lambda a,b:a+b, v)
        m=sum/self.count
        return m  

class Median_Filter(Spatial_Filter):
    def __init__(self,mask):
        super(self.__class__,self).__init__(mask)  
    
    def process(self,v):
        v.sort()
        return v[len(v)/2]  
    
    
class Q3(Question):
    def __init__(self,image,m='show'):
        super(self.__class__,self).__init__('Q3',image,m)
                
    def action(self):
        image = self.image
        s_p=Salt_Pepper(0.025,0.025)
        gaus=Gaussian(0.0,25)
    
        m=mat([
          [1,1,1],
          [1,1,1],
          [1,1,1],
          ])
  
        m2=mat([
          [1,2,1],
          [2,4,2],
          [1,2,1],
          ])
        mean_filter = Mean_Filter(m)
        mean_filter2 = Mean_Filter(m2)
        median_filter = Median_Filter(m)
    
        n_s_p  = s_p(image)
        n_gaus = gaus(image)
    
        self.display(n_gaus,'Gaussian_Noise')
        self.display(n_s_p,'Salt_Pepper_Noise')
    
        self.display(mean_filter(n_gaus),'Mean_Filter_Gaussian_Noise')
        self.display(median_filter(n_gaus),'Med_Filter_Gaussian_Noise')
    
        self.display(mean_filter(n_s_p),'Mean_Filter_S_P_Noise')
        self.display(median_filter(n_s_p),'Med_Filter_S_P_Noise')
        

    
if __name__ == '__main__':
    q = Q3('fig4.jpg','save')
    q()
    
    